/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution{
public:
  int diameterOfBinaryTree(TreeNode *root){

    int d = 0;
    dfs(root, d);

    return d;

  }

  int dfs(TreeNode *root, int &d){

    if(!root){
      return 0;
    }

    int left = dfs(root->left, d);
    int right = dfs(root->right, d);

    d = max(d, left + right); // 保存最大值

    return 1 + max(left, right);

  }
};